<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>HTML5 Canvas小游戏 - 贪吃蛇</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            flex-direction: column;
            align-items: center;
            padding: 20px;
            color: white;
        }

        header {
            text-align: center;
            margin-bottom: 20px;
            padding: 20px;
            width: 100%;
        }

        h1 {
            font-size: 2.5rem;
            margin-bottom: 10px;
            text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
        }

        .game-info {
            display: flex;
            justify-content: space-between;
            width: 500px;
            margin-bottom: 15px;
            font-size: 1.2rem;
            background: rgba(255, 255, 255, 0.1);
            padding: 10px 20px;
            border-radius: 10px;
            backdrop-filter: blur(10px);
        }

        .game-container {
            position: relative;
            width: 500px;
            height: 500px;
            margin: 0 auto;
        }

        #gameCanvas {
            background: rgba(0, 0, 0, 0.8);
            border-radius: 10px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
        }

        .controls {
            margin-top: 20px;
            text-align: center;
        }

        button {
            background: linear-gradient(45deg, #ff6b6b, #ffa502);
            border: none;
            padding: 12px 30px;
            font-size: 1.1rem;
            color: white;
            border-radius: 50px;
            cursor: pointer;
            margin: 0 10px;
            transition: all 0.3s ease;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
        }

        button:hover {
            transform: translateY(-3px);
            box-shadow: 0 6px 20px rgba(0, 0, 0, 0.3);
        }

        .instructions {
            background: rgba(255, 255, 255, 0.1);
            padding: 20px;
            border-radius: 10px;
            margin-top: 20px;
            max-width: 500px;
            backdrop-filter: blur(10px);
        }

        .instructions h2 {
            margin-bottom: 10px;
            text-align: center;
        }

        .instructions ul {
            padding-left: 20px;
        }

        .instructions li {
            margin-bottom: 8px;
        }

        .game-over {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.8);
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            border-radius: 10px;
            display: none;
        }

        .game-over h2 {
            font-size: 3rem;
            color: #ff6b6b;
            margin-bottom: 20px;
        }

        .final-score {
            font-size: 1.5rem;
            margin-bottom: 30px;
        }

        footer {
            margin-top: 30px;
            text-align: center;
            padding: 20px;
            font-size: 0.9rem;
            opacity: 0.8;
        }

        @media (max-width: 550px) {
            .game-container, #gameCanvas {
                width: 95vw;
                height: 95vw;
                max-width: 400px;
                max-height: 400px;
            }
            
            .game-info {
                width: 95vw;
                max-width: 400px;
            }
            
            h1 {
                font-size: 2rem;
            }
        }
    </style>
</head>
<body>
    <header>
        <h1>🐍 贪吃蛇游戏</h1>
        <p>经典游戏的HTML5 Canvas版本</p>
    </header>
    
    <div class="game-info">
        <div class="score">得分: <span id="score">0</span></div>
        <div class="high-score">最高分: <span id="highScore">0</span></div>
    </div>
    
    <div class="game-container">
        <canvas id="gameCanvas" width="500" height="500"></canvas>
        <div class="game-over" id="gameOver">
            <h2>游戏结束</h2>
            <div class="final-score">最终得分: <span id="finalScore">0</span></div>
            <button id="restartButton">重新开始</button>
        </div>
    </div>
    
    <div class="controls">
        <button id="startButton">开始游戏</button>
        <button id="pauseButton">暂停游戏</button>
    </div>
    
    <div class="instructions">
        <h2>游戏说明</h2>
        <ul>
            <li>使用 <strong>方向键</strong> 或 <strong>WASD</strong> 控制蛇的移动方向</li>
            <li>吃到食物可以增加得分并使蛇变长</li>
            <li>撞到墙壁或自己的身体游戏结束</li>
            <li>按 <strong>P</strong> 键可以暂停/继续游戏</li>
            <li>刷新页面可以重新开始游戏</li>
        </ul>
    </div>
    
    <footer>
        <p>HTML5 Canvas 贪吃蛇游戏 | 使用方向键控制 | &copy; 2023</p>
    </footer>

    <script>
        // 游戏变量
        const canvas = document.getElementById('gameCanvas');
        const ctx = canvas.getContext('2d');
        const scoreElement = document.getElementById('score');
        const highScoreElement = document.getElementById('highScore');
        const finalScoreElement = document.getElementById('finalScore');
        const gameOverElement = document.getElementById('gameOver');
        const startButton = document.getElementById('startButton');
        const pauseButton = document.getElementById('pauseButton');
        const restartButton = document.getElementById('restartButton');
        
        // 游戏设置
        const gridSize = 20;
        const tileCount = canvas.width / gridSize;
        
        // 游戏状态
        let snake = [];
        let food = {};
        let dx = 0; // 水平移动速度
        let dy = 0; // 垂直移动速度
        let score = 0;
        let highScore = localStorage.getItem('snakeHighScore') || 0;
        let gameRunning = false;
        let gamePaused = false;
        let gameLoop;
        
        // 初始化游戏
        function initGame() {
            // 初始化蛇
            snake = [
                {x: 10, y: 10}, // 蛇头
                {x: 9, y: 10},
                {x: 8, y: 10}  // 蛇尾
            ];
            
            // 初始化食物
            placeFood();
            
            // 初始化移动方向
            dx = 1;
            dy = 0;
            
            // 重置分数
            score = 0;
            scoreElement.textContent = score;
            highScoreElement.textContent = highScore;
            
            // 隐藏游戏结束界面
            gameOverElement.style.display = 'none';
        }
        
        // 放置食物
        function placeFood() {
            food = {
                x: Math.floor(Math.random() * tileCount),
                y: Math.floor(Math.random() * tileCount)
            };
            
            // 确保食物不会出现在蛇身上
            for (let segment of snake) {
                if (segment.x === food.x && segment.y === food.y) {
                    placeFood();
                    break;
                }
            }
        }
        
        // 绘制游戏
        function drawGame() {
            // 清空画布
            ctx.fillStyle = 'black';
            ctx.fillRect(0, 0, canvas.width, canvas.height);
            
            // 绘制网格线（可选）
            ctx.strokeStyle = '#333';
            ctx.lineWidth = 0.5;
            for (let i = 0; i < tileCount; i++) {
                ctx.beginPath();
                ctx.moveTo(i * gridSize, 0);
                ctx.lineTo(i * gridSize, canvas.height);
                ctx.stroke();
                
                ctx.beginPath();
                ctx.moveTo(0, i * gridSize);
                ctx.lineTo(canvas.width, i * gridSize);
                ctx.stroke();
            }
            
            // 绘制食物
            ctx.fillStyle = 'red';
            ctx.fillRect(food.x * gridSize, food.y * gridSize, gridSize, gridSize);
            
            // 绘制蛇
            snake.forEach((segment, index) => {
                if (index === 0) {
                    // 蛇头
                    ctx.fillStyle = '#4CAF50';
                } else {
                    // 蛇身
                    ctx.fillStyle = '#8BC34A';
                }
                ctx.fillRect(segment.x * gridSize, segment.y * gridSize, gridSize, gridSize);
                
                // 添加边框
                ctx.strokeStyle = '#388E3C';
                ctx.lineWidth = 1;
                ctx.strokeRect(segment.x * gridSize, segment.y * gridSize, gridSize, gridSize);
            });
        }
        
        // 移动蛇
        function moveSnake() {
            // 创建新的蛇头
            const head = {x: snake[0].x + dx, y: snake[0].y + dy};
            
            // 将新头添加到蛇数组的开头
            snake.unshift(head);
            
            // 检查是否吃到食物
            if (head.x === food.x && head.y === food.y) {
                // 增加分数
                score += 10;
                scoreElement.textContent = score;
                
                // 放置新食物
                placeFood();
            } else {
                // 移除蛇尾（如果没有吃到食物）
                snake.pop();
            }
        }
        
        // 检查碰撞
        function checkCollision() {
            const head = snake[0];
            
            // 检查是否撞墙
            if (head.x < 0 || head.x >= tileCount || head.y < 0 || head.y >= tileCount) {
                return true;
            }
            
            // 检查是否撞到自己
            for (let i = 1; i < snake.length; i++) {
                if (head.x === snake[i].x && head.y === snake[i].y) {
                    return true;
                }
            }
            
            return false;
        }
        
        // 游戏主循环
        function gameUpdate() {
            if (gamePaused) return;
            
            moveSnake();
            
            if (checkCollision()) {
                gameOver();
                return;
            }
            
            drawGame();
        }
        
        // 游戏结束
        function gameOver() {
            gameRunning = false;
            clearInterval(gameLoop);
            
            // 更新最高分
            if (score > highScore) {
                highScore = score;
                localStorage.setItem('snakeHighScore', highScore);
                highScoreElement.textContent = highScore;
            }
            
            // 显示游戏结束界面
            finalScoreElement.textContent = score;
            gameOverElement.style.display = 'flex';
        }
        
        // 开始游戏
        function startGame() {
            if (gameRunning) return;
            
            initGame();
            gameRunning = true;
            gamePaused = false;
            drawGame();
            
            // 设置游戏循环
            clearInterval(gameLoop);
            gameLoop = setInterval(gameUpdate, 150);
            
            startButton.textContent = "重新开始";
        }
        
        // 暂停/继续游戏
        function togglePause() {
            if (!gameRunning) return;
            
            gamePaused = !gamePaused;
            pauseButton.textContent = gamePaused ? "继续游戏" : "暂停游戏";
        }
        
        // 键盘控制
        function handleKeyPress(e) {
            // 如果游戏未运行或已暂停，忽略方向键
            if (!gameRunning || gamePaused) return;
            
            // 防止蛇反向移动
            switch(e.key) {
                case 'ArrowUp':
                case 'w':
                case 'W':
                    if (dy === 0) {
                        dx = 0;
                        dy = -1;
                    }
                    break;
                case 'ArrowDown':
                case 's':
                case 'S':
                    if (dy === 0) {
                        dx = 0;
                        dy = 1;
                    }
                    break;
                case 'ArrowLeft':
                case 'a':
                case 'A':
                    if (dx === 0) {
                        dx = -1;
                        dy = 0;
                    }
                    break;
                case 'ArrowRight':
                case 'd':
                case 'D':
                    if (dx === 0) {
                        dx = 1;
                        dy = 0;
                    }
                    break;
                case 'p':
                case 'P':
                    togglePause();
                    break;
            }
        }
        
        // 事件监听器
        document.addEventListener('keydown', handleKeyPress);
        startButton.addEventListener('click', startGame);
        pauseButton.addEventListener('click', togglePause);
        restartButton.addEventListener('click', startGame);
        
        // 初始化高分显示
        highScoreElement.textContent = highScore;
        
        // 初始绘制
        initGame();
        drawGame();
    </script>
</body>
</html>
